const router = require("koa-router")();
const {
  addressCreate,
  getAllAddress,
  getOneAddress,
  getOneAndUpdate,
} = require("../control/addressControl");
const { SuccessModel, ErrorModel } = require("../messageModel/index");
const loginCheck = require("../middleware/loginCheck");

router.prefix("/api/user/address");

//创建地址
router.post("/", loginCheck, async (ctx, next) => {
  const data = ctx.request.body;
  const { username } = ctx.session.userInfo;
  //创建地址操作
  const res = addressCreate(username, data);
  if (res) {
    ctx.body = new SuccessModel("注册地址成功");
  } else {
    ctx.body = new ErrorModel(-1, "注册地址失败");
  }
});

//获取地址列表
router.get("/", loginCheck, async (ctx, next) => {
  const { username } = ctx.session.userInfo;
  const res = await getAllAddress(username);
  if (res) {
    ctx.body = new SuccessModel(res);
  } else {
    ctx.body = new ErrorModel("获取地址失败");
  }
});

//获取单个地址
router.get("/:id", loginCheck, async (ctx, next) => {
  const id = ctx.params.id;
  const res = await getOneAddress(id);
  if (res) {
    ctx.body = new SuccessModel(res);
  } else {
    ctx.body = new ErrorModel("获取单个地址失败");
  }
});

//更新收货地址
router.patch("/:id", loginCheck, async (ctx, next) => {
  const id = ctx.params.id;
  const data = ctx.request.body;
  const { username } = ctx.session.userInfo;
  const res = await getOneAndUpdate(id, username, data);
  if (res) {
    ctx.body = new SuccessModel(res);
  } else {
    ctx.body = new ErrorModel("获取单个地址失败");
  }
});

module.exports = router;
